package com.kstech.ks_gaz01.manager

import android.content.Context
import com.kstech.ks_gaz01.XML_CONFIG
import com.kstech.ks_gaz01.XML_REALTIME
import com.kstech.ks_gaz01.XML_REALTIME_FLOAT
import com.kstech.ks_gaz01.XML_SENSORSET
import com.kstech.ks_gaz01.XML_SIMULATION
import com.kstech.ks_gaz01.XML_VERSION
import com.kstech.ks_gaz01.XML_XMLSETTING
import com.kstech.ks_gaz01.XML_XS_RTB
import com.kstech.ks_gaz01.XML_ZTPROGRESS
import com.kstech.ks_gaz01.data.DebugDataBean
import com.kstech.ks_gaz01.data.DebugDataBean.afterLoadXml
import com.kstech.ks_gaz01.data.DebugDataBean.dataList_ztProgress
import com.kstech.ks_gaz01.data.DebugDataBean.xmlSettings
import com.kstech.ks_gaz01.data.ZtProgressObject
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlPullParserFactory
import java.io.FileNotFoundException
import java.io.IOException


/**
 * author: lenovo
 * created on: 2023/10/27 16:08
 * description:
 *
 * xml格式
 * parent-child-group-item 四级
 *
 */
class ParseXmlManager {
    private val TAG: String = "ParseXmlManager"
    fun getXmlPullParser(context: Context, xmlFileName: String): XmlPullParser? {
        if (!xmlFileName.contains(".xml")) throw Exception("${TAG}:xml文件名称传入不合法")
        var pullParser: XmlPullParser? = null
        // 创建Pull解析器
        pullParser = XmlPullParserFactory.newInstance().newPullParser()
        // 设置xml数据源
        val inputStream = context.resources.assets.open("cars/$xmlFileName")
        pullParser.setInput(inputStream, null)
        return pullParser
    }

    /*
    * 这里介绍两种PULL解析器，XmlPullParser和XmlResourceParser，其中后者是前者的子类。
    * */
    fun pullParseXml(context: Context, xmlFileName: String) {
        val pullParser: XmlPullParser =
            getXmlPullParser(context, xmlFileName) ?: throw Exception("文件目录加载或者初始化异常")
        var parent: DebugDataBean.Parent? = null
        var child: DebugDataBean.Parent.Child? = null
        var group: DebugDataBean.Parent.Child.Group? = null
        var item: DebugDataBean.Item? = null
        var xmlTag: String? = null
        try {
            var eventType: Int = pullParser.eventType
            // 开始解析。如果解析遇到的事件是文件解析结束的话就退出循环
            while (eventType != XmlPullParser.END_DOCUMENT) {
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                        // 开始解析，可以在这里做一些初始化
                        xmlSettings = HashMap()
                    }
                    //只有START_TAG END_TAG 中才可以获得 name 不然都是null
                    XmlPullParser.START_TAG -> {
                        val currentNodeName: String = pullParser.name
                        // 开始解析某个节点
                        if (currentNodeName == "item") {//todo xml文件数据暂时 必须有para0 到5，否则会崩溃
                            when (xmlTag) {
                                XML_XMLSETTING -> {
                                    val name: String = pullParser.getAttributeValue(null, "name")
                                    val value: Boolean =
                                        pullParser.getAttributeValue(null, "value").toBoolean()
                                    xmlSettings[name] = value
                                }

                                XML_ZTPROGRESS -> {
                                    val idStr1: String = pullParser.getAttributeValue(null, "para0")
//                                    "idStr1:$idStr1"
                                    dataList_ztProgress.add(idStr1)
                                }

                                else -> {
                                    // 开始节点是“person”,则开始一个新Person的解析
                                    item = DebugDataBean.Item()
//                                  // 获取属性
//                                  pullParser.getProperty()
                                    val idStr1: String = pullParser.getAttributeValue(null, "para0")
                                    item.para0 = idStr1
//                                  Log.e("blankii", idStr1)
                                    val idStr2: String = pullParser.getAttributeValue(null, "para1")
                                    item.para1 = idStr2
                                    val idStr3: String = pullParser.getAttributeValue(null, "para2")
                                    item.para2 = idStr3
                                    val idStr4: String = pullParser.getAttributeValue(null, "para3")
                                    item.para3 = idStr4
                                    val idStr5: String = pullParser.getAttributeValue(null, "para4")
                                    item.para4 = idStr5
                                    val idStr6: String = pullParser.getAttributeValue(
                                        null, "para5"
                                    )
                                    item.isNegativeNumber = idStr6.contains("-")
                                    item.para5 = idStr6
                                }
                            }
                        } else if (currentNodeName == "parent") {
                            parent = DebugDataBean.Parent()
                            parent.xmlTag = xmlTag!!
                            parent.childList = ArrayList()
                            parent.itemList = ArrayList()
                            parent.name = pullParser.getAttributeValue(null, "name")
                            parent.sensorSetModel =
                                pullParser.getAttributeValue(null, "sensorSetModel")
//                            "${parent.name}".logd("xml-解析")
                        } else if (currentNodeName == "child") {
                            child = DebugDataBean.Parent.Child()
//                            val attrCount = pullParser.attributeCount
//                            if (attrCount >= 2) {
//                                child.itemsAddress =
//                                    pullParser.getAttributeValue(null, "itemsAddress")
//                            }
                            child.itemList = ArrayList()
                            child.groupList = ArrayList()
                            child.name = pullParser.getAttributeValue(null, "name")
                        } else if (currentNodeName == "group") {
                            group = DebugDataBean.Parent.Child.Group()
//                            val attrCount = pullParser.attributeCount
//                            if (attrCount >= 1) {
//                                group.itemsAddress =
//                                    pullParser.getAttributeValue(null, "itemsAddress")
//                            }
                            group.itemList = ArrayList()
                            group.name = pullParser.getAttributeValue(null, "name")
                        } else if (currentNodeName == XML_XMLSETTING || currentNodeName == XML_SIMULATION || currentNodeName == XML_CONFIG || currentNodeName == XML_REALTIME_FLOAT || currentNodeName == XML_REALTIME || currentNodeName == XML_SENSORSET || currentNodeName == XML_VERSION || currentNodeName == XML_ZTPROGRESS) {
                            when (currentNodeName) {
                                XML_ZTPROGRESS -> {
                                    dataList_ztProgress = ArrayList()
                                    val sMin = pullParser.getAttributeValue(null, "sMin").toInt()
                                    val cMin = pullParser.getAttributeValue(null, "cMin").toInt()
                                    val cMin1 = pullParser.getAttributeValue(null, "cMin1").toInt()
                                    val cMin2 = pullParser.getAttributeValue(null, "cMin2").toInt()
                                    val sMax = pullParser.getAttributeValue(null, "sMax").toInt()
                                    DebugDataBean.dataConfig_ZtProgress =
                                        ZtProgressObject(sMin, cMin, cMin1, cMin2, sMax)
                                }

                                XML_REALTIME_FLOAT -> {
                                    val keyIsExistRt = xmlSettings[XML_XS_RTB]
                                    if (keyIsExistRt != null && keyIsExistRt) {
                                        DebugDataBean.floatDataType =
                                            pullParser.getAttributeValue(null, "type")
                                    }
                                }
                            }
                            xmlTag = currentNodeName
                        } else if (currentNodeName == "message") {
                            parent!!.msgList = ArrayList()
                        } else if (currentNodeName == "msg") {
                            val msg = pullParser.getAttributeValue(null, "name")
                            parent!!.msgList!!.add(msg)
                        } else if (currentNodeName == "bits") {
                            item!!.bitArray = ArrayList()
                        } else if (currentNodeName == "bit") {
                            val bitName = pullParser.getAttributeValue(null, "name")
//                            bitName.loge("jjjjjjjjjj")
                            item!!.bitArray.add(bitName)
                        }
                    }

                    XmlPullParser.END_TAG -> {
                        val currentNodeName: String = pullParser.name
                        // 结束某个节点的解析
                        if (currentNodeName == "item") {
                            if (group != null) {// 如果是group包裹item
                                group.itemList.add(item!!)
                            } else if (child != null) {// 如果是child包裹item
                                child.itemList!!.add(item!!)
                            } else if (parent != null) {// 如果是parent包裹item
                                parent!!.itemList!!.add(item!!)
                            }
                        } else if (currentNodeName == "parent") {
                            DebugDataBean.xmlMap[xmlTag]!!.add(parent!!)
                            parent = null
                        } else if (currentNodeName == "child") {
                            parent!!.childList!!.add(child!!)
                            child = null
                        } else if (currentNodeName == "group") {
                            child!!.groupList!!.add(group!!)
                            group = null
                        }
                    }

                    XmlPullParser.END_DOCUMENT -> {

                    }

                    else -> {}
                }
                // 继续解析下一个事件
                eventType = pullParser.next()
            }
        } catch (e: XmlPullParserException) {
            e.printStackTrace()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
//        Log.e("blankii", "xml parse is finished")
//        val map = DebugDataBean.xmlMap
        afterLoadXml()
    }
}